const webDataUtil = require('../util/webDataUtil')
const { numberUtil } = require('../util')

exports.getFuturesAccount = async () => {
  const result = await webDataUtil.binance('getFuturesAccount')
  const myBalance = result.data || {}
  myBalance.totalInitialMargin = parseFloat(myBalance.totalInitialMargin) || 0
  // 总金额不包含收益
  myBalance.totalWalletBalance = parseFloat(myBalance.totalWalletBalance) || 0
  // 原始的（不会被仓位配置修改的）
  myBalance.rawTotalWalletBalance = myBalance.totalWalletBalance
  // 收益
  myBalance.totalUnrealizedProfit = parseFloat(myBalance.totalUnrealizedProfit) || 0
  // 总金额包含收益
  myBalance.totalMarginBalance = parseFloat(myBalance.totalMarginBalance) || 0
  // 可用金额
  myBalance.availableBalance = parseFloat(myBalance.availableBalance) || 0
  myBalance.totalPositionInitialMargin = parseFloat(myBalance.totalPositionInitialMargin) || 0
  myBalance.totalPositionBalance = 0
  // 有仓位的
  const hasPositionSymbolList = []
  const positionsList = myBalance.positions || []
  const positionMap = {}
  myBalance.kongUsdt = 0
  myBalance.kongCount = 0
  myBalance.duoUsdt = 0
  myBalance.duoCount = 0
  positionsList.forEach((v) => {
    // 数量（只有数量是不会跟着变的）
    v.positionAmt = parseFloat(v.positionAmt) || 0
    // usdt（包含盈亏，会跟着市值在变）
    v.notional = parseFloat(v.notional) || 0
    // 目前看就收益和数量最准
    v.unrealizedProfit = parseFloat(v.unrealizedProfit) || 0
    // 保证金（保证金也会跟着市值在变）
    v.initialMargin = parseFloat(v.initialMargin) || 0
    let notionalAb = Math.abs(v.notional)
    myBalance.totalPositionBalance += notionalAb
    if (notionalAb < 1) {
      notionalAb = 1
    }
    v.leverage = Math.round(Math.abs(v.notional) / v.initialMargin)
    // 相对于持仓金额的收益率
    v.incomeRate = numberUtil.countRate(v.unrealizedProfit, notionalAb)
    // 相对于保证金的收益率（币安上展示的就是这个，我对着算过一遍，值对得上）
    v.incomeMarginRate = numberUtil.countRate(v.unrealizedProfit, v.initialMargin)
    // 相对于总资产的
    v.incomeAssetRate = numberUtil.countRate(v.unrealizedProfit, myBalance.totalWalletBalance)
    // 入场价格
    v.costPrice = numberUtil.keepEightDecimals(((v.notional - v.unrealizedProfit) / v.positionAmt) || 0)
    // 最原始的买入金额
    v.costUsdt = numberUtil.keepTwoDecimals(v.notional - v.unrealizedProfit)
    v.hasPosition = Math.abs(v.notional) > 2
    v.hasDuoPosition = v.hasPosition && v.notional > 0
    v.hasKongPosition = v.hasPosition && v.notional < 0
    if (v.hasDuoPosition) {
      myBalance.duoUsdt += notionalAb
      myBalance.duoCount++
    }
    if (v.hasKongPosition) {
      myBalance.kongUsdt += notionalAb
      myBalance.kongCount++
    }
    positionMap[v.symbol] = v
    if (Math.abs(v.notional) >= 1) {
      hasPositionSymbolList.push(v.symbol)
    }
  })
  myBalance.positionMap = positionMap
  myBalance.hasPositionSymbolList = hasPositionSymbolList
  myBalance.duoUsdt = numberUtil.keepFourDecimals(myBalance.duoUsdt)
  myBalance.kongUsdt = numberUtil.keepFourDecimals(myBalance.kongUsdt)
  return myBalance
}

exports.futuresMarketBuy = async (
  {
    usdtKey,
    quantity,
    btbItem,
    btbLeverage
  }
) => {
  if (!quantity) {
    return false
  }
  await webDataUtil.binance('futuresLeverage', {
    key: usdtKey,
    quantity: btbLeverage || 1
  })
  // 执行
  const buyRes = await webDataUtil.binance('futuresMarketBuy', {
    key: usdtKey,
    quantity: quantity
  })
  const resData = buyRes.data || {}
  if (!resData.orderId) {
    return false
  }
  return resData
}

exports.futuresMarketSell = async (
  {
    usdtKey,
    quantity,
    btbItem,
    btbLeverage
  }
) => {
  if (!quantity) {
    return false
  }
  await webDataUtil.binance('futuresLeverage', {
    key: usdtKey,
    quantity: btbLeverage || 1
  })
  // 卖出
  const sellRes = await webDataUtil.binance('futuresMarketSell', {
    key: usdtKey,
    quantity: quantity
  })
  const resData = sellRes.data || {}
  if (!resData.orderId) {
    return false
  }
  return resData
}

exports.futuresBuy = async (
  {
    usdtKey,
    quantity,
    price
  }
) => {
  if (!quantity) {
    return false
  }
  // 执行
  const buyRes = await webDataUtil.binance('futuresBuy', {
    key: usdtKey,
    quantity: quantity,
    price: price
  })
  const resData = buyRes.data || {}
  if (!resData.orderId) {
    return false
  }
  return resData
}

exports.futuresSell = async (
  {
    usdtKey,
    quantity,
    price
  }
) => {
  if (!quantity) {
    return false
  }
  // 执行
  const buyRes = await webDataUtil.binance('futuresSell', {
    key: usdtKey,
    quantity: quantity,
    price: price
  })
  const resData = buyRes.data || {}
  if (!resData.orderId) {
    return false
  }
  return resData
}

exports.futuresCancelAll = async (key) => {
  return webDataUtil.binance('futuresCancelAll', {
    key: key
  })
}

exports.futuresAllOrders = async () => {
  return webDataUtil.binance('futuresAllOrders').then((res) => {
    return res.data || []
  })
}
